<template>
  <el-dialog
    :title="type == 'login' ? '登录' : '注册'"
    :width="isMobile ? '90%' : '50%'"
    v-model="state.dialogDodel"
    @close="cancel"
    :show-close="true"
  >
    <el-form>
      <el-formItem label="邮箱" :label-width="state.formLabelWidth">
        <el-input
          v-model="state.params.email"
          placeholder="邮箱"
          autocomplete="off"
        >
        </el-input>
      </el-formItem>
      <el-formItem label="密码" :label-width="state.formLabelWidth">
        <el-input
          type="password"
          placeholder="密码"
          v-model="state.params.password"
          autocomplete="off"
        ></el-input>
      </el-formItem>
      <el-formItem
        v-if="type === 'register'"
        label="昵称"
        :label-width="state.formLabelWidth"
      >
        <el-input
          v-model="state.params.name"
          placeholder="用户名或昵称"
          autocomplete="off"
        ></el-input>
      </el-formItem>
      <el-formItem
        v-if="type === 'register'"
        label="手机"
        :label-width="state.formLabelWidth"
      >
        <el-input
          v-model="state.params.phone"
          placeholder="手机号"
          autocomplete="off"
        ></el-input>
      </el-formItem>
      <el-formItem
        v-if="type === 'register'"
        label="简介"
        :label-width="state.formLabelWidth"
      >
        <el-input
          v-model="state.params.desc"
          placeholder="个人简介"
          autocomplete="off"
        ></el-input>
      </el-formItem>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="success" @click="handleOAuth">github 授权登录</el-button>
      <el-button
        v-if="type === 'login'"
        :loading="state.btnLoading"
        type="primary"
        @click="beforeSubmit"
        >登 录</el-button
      >
      <el-button
        v-else
        :loading="state.btnLoading"
        type="primary"
        @click="beforeSubmit"
        >注 册</el-button
      >
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
// import { key } from '../store'
import { useStore } from "vuex"
import { Login, Register } from "../api/api";
import { ElMessage } from "element-plus";
import { LogOrRegParams, UserInfo } from "../type/index";
import { defineProps, defineEmits, watch, reactive, onMounted, computed } from "vue";
import { useRoute, useRouter } from "vue-router";
const router = useRouter();
const emit = defineEmits(["submit", "cancel"]);
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  type: {
    type: String,
  },
  isMobile: {
    type: Boolean,
    default: false,
  },
});
const store = useStore();
const state = reactive({
  res: null,
  dialogDodel: props.visible,
  btnLoading: false,
  loading: false,
  formLabelWidth: props.isMobile ? "40px" : "60px",
  params: {
    email: "",
    name: "",
    password: "",
    phone: "",
    descri: "",
  } as LogOrRegParams,
});

const beforeSubmit = (): void => {
  const reg = new RegExp(
    "^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$"
  ); //正则表达式
  if (!state.params.email) {
    ElMessage({
      message: "邮箱不能为空！",
      type: "warning",
    });
    return;
  } else if (!reg.test(state.params.email)) {
    ElMessage({
      message: "请输入格式正确的邮箱！",
      type: "warning",
    });
    return;
  }
  if (props.type === "register") {
    if (!state.params.password) {
      ElMessage({
        message: "密码不能为空！",
        type: "warning",
      });
      return;
    } else if (!state.params.name) {
      ElMessage({
        message: "用户名不能为空！",
        type: "warning",
      });
      return;
    }
    const re =
      /^(((13[0-9]{1})|(15[0-9]{1})|(17[0-9]{1})|(18[0-9]{1}))+\d{8})$/;
    if (state.params.phone && !re.test(state.params.phone)) {
      ElMessage({
        message: "请输入正确的手机号!",
        type: "warning",
      });
      return;
    }
  }
  submit();
};
//登录注册表单提交
const submit = async (): Promise<void> => {
  // console.log(state.params)
  state.btnLoading = true;
  if (props.type === "register") {
    // data = await service.post(urls.register, state.params);
    state.res = await Register(state.params);
  } else {
    // data = await service.post(urls.login, state.params);
    state.res = await Login(state.params);
    // .then(res=>{
    //   if(res.code===0){

    //   }
    // })
    // .catch(err=>{console.log(err)})
  }
  state.btnLoading = false;
  // console.log(state.res)
  if (state.res.code === 0) {
    const userInfo: UserInfo = {
      _id: state.res.data._id,
      name: state.res.data.name,
      avatar: state.res.data.avatar,
    };
    // console.log(store);
      store.commit("saveUser", {
      userInfo,
    });
    window.localStorage.userInfo = JSON.stringify(userInfo);
    window.localStorage.blogToken=state.res.data.token
    ElMessage({
      message: state.res.message,
      type: "success",
    });
    router.go(0)
  } else {
    ElMessage({
      message: state.res.message,
      type: "warning",
    });
  }
  emit("submit", false);
};

//github授权登录
const handleOAuth = (): void => {};
const cancel = (): boolean => {
  emit("cancel", false);
  return false;
};

//使用watch观察visible
watch(props, (val, oldVal) => {
  state.dialogDodel = val.visible;
});


</script>

<style scoped lang="less">
.dialog-footer {
  text-align: right;
}
</style>
